<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Demo</title>
    <script src="js/three.js"></script>
    <script src="js/OrbitControls.js"></script>
    <script src="js/libs/stats.min.js"></script>
    <script src="js/libs/ThreeBSP.js"></script>
    <script src="js/loader/DDSLoader.js"></script>
    <script src="js/loader/MTLLoader.js"></script>
    <script src="js/loader/OBJLoader.js"></script>
</head>
<body>

<div id="container"></div>
<script>

    var stats;
    var container
    var camera, controls, scene, renderer,INTERSECTED;
    var raycaster = new THREE.Raycaster();
    var mouse = new THREE.Vector2();
    var onClickPosition = new THREE.Vector2();
    var closed = -0.01;
    var opened = -(Math.PI/2-0.01);
    var light,light2,lightHelper;
    init();
    animate(); // remove when using next line for animation loop (requestAnimationFrame)
    //animate();

    function init() {

        scene = new THREE.Scene();

        renderer = new THREE.WebGLRenderer();
        renderer.setClearColor( 0xffffff);
        renderer.setPixelRatio( window.devicePixelRatio );
        renderer.setSize( window.innerWidth, window.innerHeight );
        renderer.shadowMapEnabled = true;

        container = document.getElementById( 'container' );
        container.appendChild( renderer.domElement );

        camera = new THREE.PerspectiveCamera( 60, window.innerWidth / window.innerHeight, 1, 10000 );
        camera.position.z = 2000;

        controls = new THREE.OrbitControls( camera, renderer.domElement );
        controls.addEventListener( 'change', render ); // remove when using animation loop
        // enable animation loop when using damping or autorotation
        //controls.enableDamping = true;
        //controls.dampingFactor = 0.25;
        controls.enableZoom = true;

        // world

        var textureLoader = new THREE.TextureLoader();

        //geometry part

        var floorGeo = new THREE.CubeGeometry(1600,1300,10);
        var floorMat ;
        var floorMesh;

        textureLoader.load('model/texture/floor.png', function(tex) {
            floorMat = new THREE.MeshLambertMaterial({map:tex, color:0xBEC9BE, emissive:0xBEC9BE,emissiveIntensity:0.005, overdraw: false});
            floorMat.map.wrapS = THREE.RepeatWrapping;
            floorMat.map.wrapT = THREE.RepeatWrapping;
            floorMat.map.repeat.set(13,10);
            floorMesh = new THREE.Mesh(floorGeo,floorMat);
            floorMesh.position.x=600;
            floorMesh.position.y=450;
            floorMesh.receiveShadow=true;
            scene.add(floorMesh);
        });





        var shape = new THREE.Shape();
        shape.moveTo(0, 0);
        // straight line upwards
        shape.lineTo(1000, 0);
        shape.lineTo(1000, 500);
        shape.lineTo(500, 500);
        shape.lineTo(500, 1000);
        shape.lineTo(0, 1000);
        shape.lineTo(0, 0);
        var outShape=new THREE.Shape();
        outShape.moveTo(-30, -30);
        outShape.lineTo(1030, -30);
        outShape.lineTo(1030, 530);
        outShape.lineTo(530, 530);
        outShape.lineTo(530, 1030);
        outShape.lineTo(-30, 1030);
        outShape.lineTo(-30, -30);
        var options = {
            amount: 275
        };

        var wallGeo = new THREE.ExtrudeGeometry(shape,options);
        var wallMat = new THREE.MeshBasicMaterial({color:0x002288});
        var wallMesh = new THREE.Mesh(wallGeo,wallMat);
        var outwallGeo = new THREE.ExtrudeGeometry(outShape,options);
        var outwallMat = new THREE.MeshBasicMaterial({color:0x002288});
        var outwallMesh = new THREE.Mesh(outwallGeo,outwallMat);

        var doorGeo1 = new THREE.CubeGeometry(150,90,200);
        var doorMat1 = new THREE.MeshBasicMaterial({color:0xff0000});
        var door1    = new THREE.Mesh(doorGeo1,doorMat1);
        door1.position.x = 100;
        door1.position.z = 105;


        var winGeo1 = new THREE.CubeGeometry(600,80,150);
        var winMat1 = new THREE.MeshBasicMaterial({color:0xff0000});
        var win1    = new THREE.Mesh(winGeo1,winMat1);
        win1.position.x = 600;
        win1.position.z = 145;
//        scene.add(win1);

//        scene.add(outwallMesh);
        var wallBSP = new ThreeBSP(wallMesh);
        var outwallBSP = new ThreeBSP(outwallMesh);
        var door1BSP = new ThreeBSP(door1);
        var win1BSP = new ThreeBSP(win1);
        var resultBSP = outwallBSP.subtract(wallBSP);
        resultBSP = resultBSP.subtract(door1BSP).subtract(win1BSP);

//        var cubeMaterial = new THREE.MeshDepthMaterial();
//        var colorMaterial = new THREE.MeshBasicMaterial({
//            color: 0xB0C4e6,
//            transparent: true,
//            blending: THREE.MultiplyBlending
//        });

//        var group = new THREE.Group();
//        var result1 = resultBSP.toMesh(cubeMaterial);
//        var result2 = resultBSP.toMesh(colorMaterial);
//        group.add(result1);
//        group.add(result2);
//        group.castShadow=true;
//        scene.add(group);
//        var result = resultBSP.toMesh(
//            new THREE.MeshLambertMaterial({
//            shading: THREE.SmoothShading,
//            color: 0xB0C4e6}));
        var result = resultBSP.toMesh();
        result.castShadow=true;
        result.name="wall";

        var map = THREE.ImageUtils.loadTexture('model/texture/outside_lightmap.jpg');
        var faces = result.geometry.faces;

        result.geometry.faceVertexUvs[0] = [];
        result.geometry.faceVertexUvs[1] = [];
        console.log("length:"+faces.length);
        for (var i = 0; i < faces.length ; i++) {

            var v1 = result.geometry.vertices[faces[i].a],
                    v2 = result.geometry.vertices[faces[i].b],
                    v3 = result.geometry.vertices[faces[i].c];
            console.log("length:"+v1.x+"-"+v2.x+"-"+v3.x);

//            if(v1.x<0 && v2.x<0 && v3.x<0){
            result.geometry.faceVertexUvs[0].push([
                new THREE.Vector2(v1.y/1000 ,v1.z/275),
                new THREE.Vector2(v2.y/1000 ,v2.z/275),
                new THREE.Vector2(v3.y/1000 ,v3.z/275)
            ]);
            result.geometry.faceVertexUvs[1].push([
                new THREE.Vector2(v1.y/1000 ,v1.z/275),
                new THREE.Vector2(v2.y/1000 ,v2.z/275),
                new THREE.Vector2(v3.y/1000 ,v3.z/275)
            ]);
//            }else{
//                result.geometry.faceVertexUvs[0].push([
//                    new THREE.Vector2(0,0),
//                    new THREE.Vector2(0,0),
//                    new THREE.Vector2(0,0)
//                ]);
//            }

        }
        result.geometry.uvsNeedUpdate = true;
        var ss = new THREE.Mesh(result.geometry,new THREE.MeshPhongMaterial({
//            color:0xB0C4e6,
            color:0xB0E2FF,
            lightMap:map

        }));
        ss.name="11";
        scene.add(ss);

//        result.geometry.computeFaceNormals();
//        result.geometry.computeVertexNormals();
//        scene.add(result);


        var windowGeo  = new THREE.CubeGeometry(600,1,150);
        var windoeMat = new THREE.MeshPhongMaterial({transparent:true,opacity:0.5,color:0xAFEEEE});
        var windowMesh = new THREE.Mesh(windowGeo,windoeMat);
        windowMesh.position.x = 600;
        windowMesh.position.y = -12;
        windowMesh.position.z = 145;
        scene.add(windowMesh);


        var doorInGeo = new THREE.CubeGeometry(150,8,200);
        var doorInMat = new THREE.MeshPhongMaterial({transparent:true,opacity:0.5,color:0xAFEEEE});
        var doorIn = new THREE.Mesh(doorInGeo,doorInMat);
//        doorIn.position.x = 100;
//        doorIn.position.z = 105;
//        doorIn.position.y = -15;
        doorIn.position.x = 75;
        doorIn.position.z = 0;
        doorIn.position.y = 0;
        doorIn.name="doorIn";
//        scene.add(doorIn);

        var doorHandleGeo = new THREE.CylinderGeometry(10,10,12);
        var doorHandleMat = new THREE.MeshLambertMaterial({color:0x8B4500});
        var doorHandle = new THREE.Mesh(doorHandleGeo,doorHandleMat);
        doorHandle.position.x = 135;
        doorHandle.position.z = 0;
        doorHandle.position.y = 0;
//        doorHandle.position.x = 160;
//        doorHandle.position.z = 105;
//        doorHandle.position.y = -15;
//        scene.add(doorHandle);
        var doorUnion = new THREE.Object3D();
        doorUnion.position.set(25,-15,105);
//        doorUnion.position.x=25;
//        doorUnion.position.y=-15;
//        doorUnion.position.z=105;
        doorUnion.add(doorIn);
        doorUnion.add(doorHandle);

        doorUnion.name='door';
//        doorUnion.rotation.z=-Math.PI/2;
        scene.add(doorUnion);
        var loader = new THREE.FontLoader();
        loader.load( 'fonts/helvetiker_regular.typeface.json', function ( response ) {

            var textGeo = new THREE.TextGeometry( "No.1", {

                font:response,
                size: 25,
                height: 15,
                curveSegments: 4,

                bevelThickness: 1,
                bevelSize: 0.5,
                bevelEnabled: false,

                material: 0,
                extrudeMaterial: 1

            });
            var textMesh = new THREE.Mesh(textGeo,new THREE.MeshBasicMaterial({color:0xdddd00}));
            textMesh.position.x=205;
            textMesh.position.y=130;
            textMesh.position.z=195;
            textMesh.rotation.z=Math.PI/2;
            scene.add(textMesh);

        } );



        var onProgress = function ( xhr ) {
            if ( xhr.lengthComputable ) {
                var percentComplete = xhr.loaded / xhr.total * 100;
                console.log( Math.round(percentComplete, 2) + '% downloaded' );
            }
        };

        var onError = function ( xhr ) { };

        THREE.Loader.Handlers.add( /\.dds$/i, new THREE.DDSLoader() );

        var mtlLoader = new THREE.MTLLoader();
        mtlLoader.setPath( 'model/emc/' );
        mtlLoader.load( 'EMC.mtl', function( materials ) {

            materials.preload();

            var objLoader = new THREE.OBJLoader();
            objLoader.setMaterials( materials );
            objLoader.setPath( 'model/emc/' );
            objLoader.load( 'EMC.obj', function ( object ) {
                object.scale.x=100;
                object.scale.y=100;
                object.scale.z=100;
                object.rotateX(Math.PI/2);
                object.rotateY(Math.PI/2);
                object.position.x = 200;
                object.position.y = 200;
                object.position.z = 5;
                scene.add( object );
                for(var i=0;i<6;i++){
                    var obj1 = object.clone();
                    obj1.position.x = 200+(i+1)*60;
                    scene.add( obj1 );

                }

            }, onProgress, onError );

        });





        light2 = new THREE.AmbientLight( 0xffffff );
        light2.intensity=0.8;
        scene.add( light2 );

        light = new THREE.DirectionalLight(0xffffff);
        light.intensity=0.6;
        light.castShadow = true;
        light.position.set( 500, 500, 1000 );

        var tar1 = new THREE.Object3D();
//         lightHelper= new THREE.SpotLightHelper(light);
        tar1.position.set(500,500,0);

        tar1.name="111";
        scene.add(tar1);

        console.log(tar1);
        light.target=tar1;

        scene.add( light );

//        scene.add( lightHelper );

        //

        stats = new Stats();
        container.appendChild( stats.dom );

        //

        window.addEventListener( 'resize', onWindowResize, false );
        container.addEventListener( 'mousemove', onMouseMove, false );
        container.addEventListener("dblclick",openClose,false);
    }

    function onWindowResize() {

        camera.aspect = window.innerWidth / window.innerHeight;
        camera.updateProjectionMatrix();

        renderer.setSize( window.innerWidth, window.innerHeight );

    }

    function animate() {

        requestAnimationFrame( animate );

        controls.update(); // required if controls.enableDamping = true, or if controls.autoRotate = true

        stats.update();

        render();

    }
//    var needOpen = 0;

    function render() {

        renderer.render( scene, camera );
//        doorSwitch(needOpen);
    }

//    function doorSwitch(on){
//        var door = scene.getObjectByName('door');
//        if(on==1){
//            door.rotation.z-=0.15;
//            if(door.rotation.z<opened){
//                needOpen=0;
//            }
//        }
//        if(on==2){
//            door.rotation.z+=0.15;
//            if(door.rotation.z>closed){
//                needOpen=0;
//            }
//        }
//    }
//    function openClose() {
//        if(INTERSECTED){
//            var door = scene.getObjectByName('door');
//            if(door.rotation.z<-(Math.PI/2-0.01)){
//                needOpen=2;
//            }
//            if(door.rotation.z>-0.01){
//                needOpen=1;
//            }
//        }
//    }



//    function onMouseMove( evt ) {
//
//        evt.preventDefault();
//
//        var array = getMousePosition( container, evt.clientX, evt.clientY );
//        onClickPosition.fromArray( array );
//        var door = scene.getObjectByName("door");
//
//        var intersects = getIntersects( onClickPosition, door.children );
//
//        if ( intersects.length > 0  ) {
//            INTERSECTED=door.getObjectByName("doorIn");
//            INTERSECTED.currentHex = INTERSECTED.material.emissive.getHex();
//
////            intersects[0].face.color=new THREE.Color(0xff0000);
//            INTERSECTED.material.color.setHex(0xff0000);
//
//
//
//
//        }else{
//
//            if(INTERSECTED)INTERSECTED.material.color.setHex(0xAFEEEE);
//
//            INTERSECTED=null;
//        }
//
//    }

//    var getMousePosition = function ( dom, x, y ) {
//
//        var rect = dom.getBoundingClientRect();
//        return [ ( x - rect.left ) / rect.width, ( y - rect.top ) / rect.height ];
//
//    }

//    var getIntersects = function ( point, objects ) {
//
//        mouse.set( ( point.x * 2 ) - 1, - ( point.y * 2 ) + 1 );
//
//        raycaster.setFromCamera( mouse, camera );
//
//        return raycaster.intersectObjects( objects );
//
//    }


</script>
</body>
</html>